extends Node2D

@onready var tileMap=$TileMap
@onready var camera=$Camera2D

# 噪声纹理
@export var heightTex:NoiseTexture2D
@export var treeTex:NoiseTexture2D
var noise:Noise
var treeNoise:Noise

# 地图里水平与垂直的格子数量
const width :=200
const height :=200

# 资源id与图块坐标
var sourceId:=0
var waterCrood:=Vector2i(0,1)
var landCrood:=Vector2i(0,0)
# 草地图块集合
var grassCroods=[ Vector2i(1,0), Vector2i(2,0), Vector2i(3,0), Vector2i(4,0), Vector2i(5,0) ]
# 椰树图块集合
var plantCroods=[
	Vector2i(12,2),
	Vector2i(15,2),
]
# 橡树图块集合
var treeCrood=Vector2i(15,6)

# 地形坐标集合
var sandArr=[]
var grassArr=[]
var cliffArr=[]

# 地形序号
enum TERRAIN{
	SAND,
	GRASS,
	DIRT,
	CLIFF,
	ENV
}
# 图层
enum LAYER{
	WATER,
	GROUND,
	GRASS,
	CLIFF,
	ENV
}


func _ready() -> void:
	noise=heightTex.noise
	treeNoise=treeTex.noise
	createWorld()

func _input(_event: InputEvent) -> void:
	var zoom=camera.zoom.x
	if Input.is_action_just_pressed('zoomIn'):
		if zoom<=0.1:return
		zoom-=0.1
	if Input.is_action_just_pressed('zoomOut'):
		zoom+=0.1
	camera.zoom=Vector2(zoom,zoom)

func createWorld()->void:
	# 遍历格子，按噪声数值放置图块
	for x in range(-width,width):
		for y in range(-height,height):
			renderTile(x,y)
	renderTerrain()

# 渲染图块
func renderTile(x,y):
	var noiseVal=noise.get_noise_2d(x,y)
	var treeVal=treeNoise.get_noise_2d(x,y)

	var crood:Vector2i=waterCrood
	var layer=LAYER.WATER

	# 陆地
	if noiseVal >= 0.0:
		sandArr.append(Vector2i(x,y))
		# 植物
		if noiseVal>0.05 and noiseVal < 0.17 and treeVal>0.8:
			crood=plantCroods.pick_random()
			layer=LAYER.ENV
		# 草地
		if noiseVal >=0.2:
			grassArr.append(Vector2i(x,y))
			# 野花
			if noiseVal>=0.25:
				layer=LAYER.GRASS
				crood=grassCroods.pick_random()
				if noiseVal<0.35 and treeVal>0.7:
					layer=LAYER.ENV
					crood=treeCrood
			# 悬崖 
			if noiseVal>=0.4:
				cliffArr.append(Vector2i(x,y))

	tileMap.set_cell(layer,Vector2(x,y),sourceId,crood)

# 渲染地形 
func renderTerrain():
	tileMap.set_cells_terrain_connect(LAYER.GROUND,sandArr,TERRAIN.SAND,0)
	tileMap.set_cells_terrain_connect(LAYER.GROUND,grassArr,TERRAIN.GRASS,0)
	tileMap.set_cells_terrain_connect(LAYER.CLIFF,cliffArr,TERRAIN.CLIFF,0)
